package com.qubuyer.business.mine.activity

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.qubuyer.R
import com.qubuyer.core.app.DataBindingFragment
import com.qubuyer.databinding.FragmentTabHostBinding

/**
 * @author Susong
 * @date 创建时间2019/6/23
 * @description 销售总额
 * @version
 */
abstract class TabHostFragment : DataBindingFragment<FragmentTabHostBinding>() {

    abstract val tabs: Array<String>

    abstract fun createFragment(position: Int): Fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dataBinding.etlTab.addTabList(tabs)
        dataBinding.viewPager.adapter =
            object : FragmentStateAdapter(childFragmentManager, lifecycle) {
                override fun getItemCount(): Int {
                    return tabs.size
                }

                override fun createFragment(position: Int): Fragment {
                    return this@TabHostFragment.createFragment(position)
                }
            }
        dataBinding.viewPager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            private var previousScrollState = 0
            private var scrollState = 0

            override fun onPageScrollStateChanged(state: Int) {
                previousScrollState = scrollState
                scrollState = state
            }

            override fun onPageSelected(position: Int) {
                val tabLayout: TabLayout = dataBinding.etlTab.tabLayout
                if (tabLayout.selectedTabPosition != position && position < tabLayout.tabCount) {
                    val updateIndicator = (scrollState == ViewPager.SCROLL_STATE_IDLE
                            || (scrollState == ViewPager.SCROLL_STATE_SETTLING
                            && previousScrollState == ViewPager.SCROLL_STATE_IDLE))
                    tabLayout.selectTab(tabLayout.getTabAt(position), updateIndicator)
                }
            }
        })
        dataBinding.etlTab.setupWithViewPager2(dataBinding.viewPager)
    }

    override fun onDataBinding(dataBinding: FragmentTabHostBinding) {
        dataBinding.host = this
    }

    override val layoutId: Int
        get() = R.layout.fragment_tab_host
}